package com.example.albumphoto

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.LinearLayout.LayoutParams
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.albumphoto.ui.theme.AlbumPhotoTheme
import org.w3c.dom.Text

class MainActivity : ComponentActivity() {
    private val TAG = "MainActivity"

    private var contentView: LinearLayout? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        contentView = this.findViewById<LinearLayout>(R.id.contentView)
        initView()
    }

    private val clickListener: View.OnClickListener = View.OnClickListener {
        var linkPhotosIdStr = it.tag?.toString()
        val title = it.findViewById<TextView>(R.id.nav_item_title).text
        linkPhotosIdStr?.let {
            val linkPhotosId = linkPhotosIdStr.toIntOrNull()
            Log.i(TAG, "linkPhotosId = $linkPhotosId  $title")
            // 传递简单数据
            val intent = Intent(this, PreviewAcvity::class.java).apply {
                putExtra(DataFactory.previewTitleKey, title)
                putExtra(DataFactory.previewPhotosIdKey, linkPhotosId)
            }
            // 普通启动
            startActivity(intent)
        }
    }

    private fun initView() {
        val srcList = DataFactory.getNavDatas(this)
        srcList.forEach {
            val itemView: View = this.layoutInflater.inflate(R.layout.nav_item_view, null)
            val iconView = itemView.findViewById<ImageView>(R.id.nav_item_img)
            val textView = itemView.findViewById<TextView>(R.id.nav_item_title)
            iconView.setImageResource(it.imageResId)
            textView.text = it.title
            itemView.tag = it.linkPhotosId
            val llp = LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
            llp.topMargin = 30
            contentView?.addView(itemView, llp)
            itemView.setOnClickListener(clickListener)
        }
    }
}

@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
    Text(
        text = "Hello $name!",
        modifier = modifier
    )
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    AlbumPhotoTheme {
        Greeting("Android")
    }
}